package com.health.work.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.mapapi.GeoPoint;


import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class AssistUtils {
    
    private static double latitude = 0.0;
    private static double longitude = 0.0;
    public static final String ACTION_LOC = "com.health.inquire.action_loc";
    public static Context mContext ;
    /**
     * 获得手机当前位置
     */
    private static void getLOC(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Log.d("guojie", "get GPS location ==");
            if (location != null) {
                Log.d("guojie", "get location ==" + location.getLatitude());
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        } else {
            Log.d("guojie", "get no location ==");
            LocationListener locationListener = new LocationListener() {

                // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
                @Override
                public void onStatusChanged(String provider, int status,
                        Bundle extras) {

                }

                // Provider被enable时触发此函数，比如GPS被打开
                @Override
                public void onProviderEnabled(String provider) {

                }

                // Provider被disable时触发此函数，比如GPS被关闭
                @Override
                public void onProviderDisabled(String provider) {

                }

                // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        Log.e("Map",
                                "Location changed : Lat: "
                                        + location.getLatitude() + " Lng: "
                                        + location.getLongitude());
                        Intent it = new Intent();
                        it.setAction(ACTION_LOC);
                        mContext.sendBroadcast(it);
                    }
                }
            };
            locationManager
                    .requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            1000, 0, locationListener);
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Log.d("guojie", "get network location ==");
            if (location != null) {
                latitude = location.getLatitude(); // 经度
                longitude = location.getLongitude(); // 纬度
            }
        }
        if ((int)latitude == 0 && (int)longitude == 0) {
            LocationListener locationListener = new LocationListener() {

                // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
                @Override
                public void onStatusChanged(String provider, int status,
                        Bundle extras) {

                }

                // Provider被enable时触发此函数，比如GPS被打开
                @Override
                public void onProviderEnabled(String provider) {

                }

                // Provider被disable时触发此函数，比如GPS被关闭
                @Override
                public void onProviderDisabled(String provider) {

                }

                // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        Log.e("Map",
                                "Location changed : Lat: "
                                        + location.getLatitude() + " Lng: "
                                        + location.getLongitude());
                    }
                }
            };
            locationManager
                    .requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            1000, 0, locationListener);
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Log.d("guojie", "get network location ==");
            if (location != null) {
                latitude = location.getLatitude(); // 经度
                longitude = location.getLongitude(); // 纬度
            }
        }
    }

    /**
     * 通过经纬度转化成当前详细位置
     * @param latitude
     * @param longitude
     * @return
     * @throws Exception
     */
    private String getLocation(double latitude, double longitude)
            throws Exception {
        String resultString = "";
        String urlString = String.format(
                "http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", latitude,
                longitude);
        Log.i("URL", urlString);
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(urlString);
        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            BufferedReader buffReader = new BufferedReader(
                    new InputStreamReader(entity.getContent()));
            StringBuffer strBuff = new StringBuffer();
            String result = null;
            while ((result = buffReader.readLine()) != null) {
                strBuff.append(result);
            }
            resultString = strBuff.toString();
            if (resultString != null && resultString.length() > 0) {
                JSONObject jsonobject = new JSONObject(resultString);
                JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
                        .toString());
                resultString = "";
                for (int i = 0; i < jsonArray.length(); i++) {
                    resultString = jsonArray.getJSONObject(i).getString(
                            "address");
                }
            }
        } catch (Exception e) {
            throw new Exception("sd:" + e.getMessage());
        } finally {
            get.abort();
            client = null;
        }
        return resultString;
    }
    /**
     * 获得当前地理位置，精确到区镇
     * @param context
     * @return
     */
    public static String getLoc_Area(Context context) {
        Geocoder geocoder = new Geocoder(context);
        List places = null;
        mContext = context;
        getLOC(context);
        try {
            // Thread.sleep(2000);
            places = geocoder.getFromLocation(latitude, longitude, 5);
            // Thread.sleep(2000);
            System.out.println(places.size() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String placename = "";
        if (places != null && places.size() > 0) {
            // placename=((Address)places.get(0)).getLocality();
            // 一下的信息将会具体到某条街
            // 其中getAddressLine(0)表示国家，getAddressLine(1)表示精确到某个区，getAddressLine(2)表示精确到具体的街
            // placename = ((Address) places.get(0)).getAddressLine(0) + ", " +
            // System.getProperty("line.separator")
            // + ((Address) places.get(0)).getAddressLine(1) + ", "
            // + ((Address) places.get(0)).getAddressLine(2);
         placename = ((Address) places.get(0)).getLocality();
            if(((Address) places.get(0)).getSubLocality()!=null)
            {
                placename = placename+((Address) places.get(0)).getSubLocality();
            } else
            {
                placename = ((Address) places.get(0)).getAddressLine(1);
            }
            return placename;
        } else {
            return "无法定位您当前位置";
        }
    }
    
    public static GeoPoint getGeoPoint(Context context)
    {
        GeoPoint p ;
        // Log.d("guojie", "latitude ==="+latitude+"longitude ====="+longitude);
        if(latitude!=0.0 && longitude!=0.0) {
            p = new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6));
        } else {
            getLOC(context);
            p = new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6));
        }
        return p;
    }
}